//
//  SAProductChooseImageView.m
//  Saas
//
//  Created by bing on 2020/1/8.
//  Copyright © 2020 bing. All rights reserved.
//

#import "SAProductChooseImageView.h"
#import "SAProductChooseImageModel.h"
#import "SAProductChooseImageCell.h"
#import "SAProductChooseAddImageCell.h"
#import <TZImagePickerController.h>
#import <AVFoundation/AVFoundation.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import <Photos/Photos.h>
#import "SAproductUploadAPI.h"
#import "HDHubView.h"

@interface SAProductChooseImageView()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout,TZImagePickerControllerDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,HTTPAPIDelegate>

@property (nonatomic,strong) NSMutableArray  *dataArray;
@property (nonatomic,strong) NSMutableArray  *dataServerArray;
@property (nonatomic,strong) UICollectionView *collectionView;
@property(nonatomic ,copy)   NSString *type;
@property (nonatomic,strong) UILabel *hitLabel;
@property (nonatomic, strong) UIImagePickerController *imagePickerController;

@property(nonatomic ,assign)   BOOL isClick;
@property (nonatomic, strong) SAproductUploadAPI *productUploadAPI;

@end
@implementation SAProductChooseImageView

#pragma mark - HTTPAPIDelegate
- (void)fetchData:(id)data fromServerSuccessedWithAPI:(HTTPAPI *)api {
    
}

- (void)fetchDataFromServerFailedWithError:(NSError *)error API:(HTTPAPI *)api {
    
}

+(instancetype)shareCornView
{
    SAProductChooseImageView * shareView = [[SAProductChooseImageView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    return shareView;
}

-(instancetype)initWithFrame:(CGRect)frame
{
    if(self = [super initWithFrame:frame])
    {
        self.userInteractionEnabled = YES;
        self.backgroundColor = kColor(0, 0, 0, 0.6);
        
        [self creatUI];
        self.isClick = YES;
        //[self loadData];
        
    }
    
    return self;
}

- (UIImagePickerController *)imagePickerController {
    if (_imagePickerController == nil) {
        _imagePickerController = [[UIImagePickerController alloc] init];
        _imagePickerController.delegate = self; //delegate遵循了两个代理
        _imagePickerController.allowsEditing = YES;
    }
    return _imagePickerController;
}

-(void)creatUI
{
    UIButton *deleteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    deleteBtn.frame = CGRectMake(0, 0, kScreenWidth, kScaleNum(157));
    [deleteBtn addTarget:self action:@selector(shareDissTapEvent) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:deleteBtn];
    
    UIView *backGroundView = [[UIView alloc] initWithFrame:CGRectMake(0, kScaleNum(157), kScreenWidth, kScreenHeight - kScaleNum(157))];
    backGroundView.backgroundColor = kColor(246, 246, 246, 1);
    backGroundView.userInteractionEnabled = YES;
    [self addSubview:backGroundView];
    //
    UILabel *hitLabel = [[UILabel alloc] init];
    hitLabel.textAlignment = NSTextAlignmentCenter;
    hitLabel.textColor = kColor(51, 51, 51, 1);
    hitLabel.font = kFont(16);
    [backGroundView addSubview:hitLabel];
    self.hitLabel = hitLabel;
    [hitLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.offset(kScaleNum(0));
        make.top.equalTo(@(kScaleNum(27)));
        make.height.mas_equalTo(kScaleNum(16));
    }];
    
    UIButton *confirmBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    confirmBtn.frame = CGRectMake(kScreenWidth - kScaleNum(80), kScaleNum(0), kScaleNum(80), kScaleNum(32));
    [confirmBtn setTitle:@"保存" forState:UIControlStateNormal];
    [confirmBtn setTitleColor:kBuleColor forState:UIControlStateNormal];
    [confirmBtn addTarget:self action:@selector(confirmationTapEvent) forControlEvents:UIControlEventTouchUpInside];
    [backGroundView addSubview:confirmBtn];
    
    UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc]init];
    // flow.headerReferenceSize = CGSizeMake(0, 200);
    flow.scrollDirection = UICollectionViewScrollDirectionVertical;
    flow.itemSize = CGSizeMake(kScaleNum(100), kScaleNum(125));
    flow.minimumInteritemSpacing = kScaleNum(10);
    //    //设置每行之间的最小间隔
    flow.minimumLineSpacing = kScaleNum(10);
    
    _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(kScaleNum(0), kScaleNum(43), kScreenWidth,kScreenHeight - kScaleNum(189)) collectionViewLayout:flow];
    _collectionView.backgroundColor = [UIColor clearColor];
    _collectionView.dataSource=self;
    _collectionView.delegate=self;
    _collectionView.showsVerticalScrollIndicator = NO;
    _collectionView.showsHorizontalScrollIndicator = NO;
    [backGroundView addSubview:_collectionView];
    [_collectionView registerClass:[SAProductChooseImageCell class] forCellWithReuseIdentifier:@"SAProductChooseImageCell"];
    [_collectionView registerClass:[SAProductChooseAddImageCell class] forCellWithReuseIdentifier:@"SAProductChooseAddImageCell"];
    
}

-(void)loadData:(NSMutableArray *)array andServeArray:(NSMutableArray *)serveArray andType:(NSString *)type
{
    self.type = type;
    
    self.hitLabel.text = type;
    
    if (array.count > 0) {
        [self.dataArray addObjectsFromArray:array];
        [self.dataServerArray addObjectsFromArray:serveArray];
        [_collectionView reloadData];
    }else
    {
        [self loadData];
    }
}


-(void)loadData
{
    
    [_collectionView reloadData];
    
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (self.dataArray.count == 0) {
        return 1;
    }else if (self.dataArray.count == 9)
    {
        return 9;
    }else
    {
        return self.dataArray.count+1;
    }
    
    
}

- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto infos:(NSArray<NSDictionary *> *)infos {
    NSMutableArray *array = [[NSMutableArray alloc] init];
    [array addObjectsFromArray:photos];
    [HDHubView loadingMessage:@"上传中..."];
    if (array.count > 0) {
        self.isClick = NO;
    }
    [self.productUploadAPI postDataWithUrl:@"" params:nil imageDatas:array success:^(id response) {
        NSLog(@"%@",response);
        if ([response[@"code"] integerValue] == 0) {
            self.isClick = YES;
            [HDHubView dismissLoading];
            [Prompt popPromptViewWithMsg:@"上传图片成功!" duration:2];
            NSArray *listArray = response[@"data"];
            for (int i=0; i<listArray.count; i++) {
                NSArray *modelArray = [listArray[i] componentsSeparatedByString:@","];
                SAProductChooseImageModel *model = [[SAProductChooseImageModel alloc] init];
                if (self.dataArray.count == 0) {
                    if (i==0) {
                        model.isSelecd = YES;
                    }else
                    {
                        model.isSelecd = NO;
                    }
                }
                model.url = modelArray[0];
                [self.dataArray addObject:model];
                
            }
            [self.dataServerArray addObjectsFromArray:listArray];
            [self.collectionView reloadData];
        }
    } failure:^(id error) {
        self.isClick = YES;
        [Prompt popPromptViewWithMsg:@"上传图片失败!" duration:2];
        [HDHubView dismissLoading];
    }];
}

-(UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.dataArray.count == 0) {
        static NSString *identifier=@"SAProductChooseAddImageCell";
        SAProductChooseAddImageCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
        cell.addImageBlock = ^{
            
            if (self.isClick == YES) {
                [[NSNotificationCenter defaultCenter] postNotificationName:@"changeRotate" object:@"1"];
                
                NSInteger Count = 9- self.dataArray.count;//剩余可选图片数量
                TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:Count columnNumber:5 delegate:self pushPhotoPickerVc:YES];
                [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photo, NSArray * assets, BOOL isSelectOriginalPhoto) {
                    for (NSInteger i = 0; i<photo.count; i++) {
                        //                    UIImage *img = [ImageUtil zipImgWithImage:photo[i]];//压缩图片
                        //                    [imgAry addObject:img];
                    }
                    
                }];
                imagePickerVc.allowPickingVideo = NO;
                imagePickerVc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
                [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:imagePickerVc animated:YES completion:nil];
                
            }
        };
        
        return cell;
    }else
    {
        if (indexPath.row <self.dataArray.count) {
            static NSString *identifier=@"SAProductChooseImageCell";
            SAProductChooseImageCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
            cell.deleteImageBlock = ^{
                [self.dataArray removeObjectAtIndex:indexPath.row];
                [self.dataServerArray removeObjectAtIndex:indexPath.row];
                if (self.dataArray.count > 0) {
                    SAProductChooseImageModel *list = self.dataArray[0];
                    list.isSelecd = YES;
                }
                [self.collectionView reloadData];
            };
            SAProductChooseImageModel *list = self.dataArray[indexPath.row];
            [cell loadData:list];
            
            return cell;
        }else
        {
            static NSString *identifier=@"SAProductChooseAddImageCell";
            SAProductChooseAddImageCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
            cell.addImageBlock = ^{
                [[NSNotificationCenter defaultCenter] postNotificationName:@"changeRotate" object:@"1"];
                NSInteger Count =  9-self.dataArray.count;//剩余可选图片数量
                TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:Count columnNumber:5 delegate:self pushPhotoPickerVc:YES];
                [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photo, NSArray * assets, BOOL isSelectOriginalPhoto) {
//                    NSMutableArray *imgAry = [@[] mutableCopy];
                    for (NSInteger i = 0; i<photo.count; i++) {
                        //                    UIImage *img = [ImageUtil zipImgWithImage:photo[i]];//压缩图片
                        //                    [imgAry addObject:img];
                    }
                    
                }];
                imagePickerVc.allowPickingVideo = NO;
                imagePickerVc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
                [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:imagePickerVc animated:YES completion:nil];
            };
            
            return cell;
        }
    }
    
    
    
}

- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    //让屏幕旋转失效
    [[UIApplication sharedApplication].keyWindow.rootViewController dismissViewControllerAnimated:YES completion:nil];
//    UIImage *editImage = info[UIImagePickerControllerEditedImage];
    // NSData *imageData = UIImageJPEGRepresentation(editImage,1.0f);
    //    NSMutableArray *array = [[NSMutableArray alloc] init];
    //    [array addObject:editImage];
    //    [SANetManager postDataWithUrl:@"http://192.168.1.70:9080/product/upload" params:nil imageDatas:array success:^(id response) {
    //        NSLog(@"%@",response);
    //    } failure:^(NSError *error) {
    //
    //    }];
    //    NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
    //
    //       dict[@"upload_file"] = array;
    //         [SANetManager requestWithType:SkyHttpRequestTypePost urlString:@"http://192.168.1.70:9080/product/upload" parameters:dict successBlock:^(id responseObject) {
    //             NSLog(@"%@",responseObject);
    //
    //
    //
    //         } failureBlock:^(NSError *error) {
    //
    //         }];
    //     [[UIApplication sharedApplication].keyWindow.rootViewController dismissViewControllerAnimated:YES completion:nil];
    [[NSNotificationCenter defaultCenter]postNotificationName:@"changeRotate" object:@"1"];
}



- (void)imagePickerControllerDidCancel:(TZImagePickerController *)picker{
    //让屏幕旋转失效
    self.isClick = YES;
    [[UIApplication sharedApplication].keyWindow.rootViewController dismissViewControllerAnimated:YES completion:nil];
    [[NSNotificationCenter defaultCenter]postNotificationName:@"changeRotate" object:@"1"];
}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    for (SAProductChooseImageModel *list in self.dataArray) {
        list.isSelecd = NO;
    }
    SAProductChooseImageModel *list = self.dataArray[indexPath.row];
    list.isSelecd = YES;
    
    [self.collectionView reloadData];
    
}

#pragma mark--UICollectionViewDelegateFlowLayout的协议方法

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    
    return UIEdgeInsetsMake(kScaleNum(10), kScaleNum(10),kScaleNum(10),kScaleNum(10));
}

-(NSMutableArray *)dataArray
{
    if(_dataArray == nil)
    {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

-(NSMutableArray *)dataServerArray
{
    if(_dataServerArray == nil)
    {
        _dataServerArray = [NSMutableArray array];
    }
    return _dataServerArray;
}

- (void)showView:(UIViewController *)Sview
{
    if(Sview==nil){
        
        [[[UIApplication sharedApplication].windows lastObject] addSubview:self];
        
    }else{
        //[view addSubview:self];
        [Sview.view addSubview:self];
    }
}

-(void)shareDissTapEvent
{
    [UIView animateWithDuration:0.5f animations:^{
        
        self.alpha = 0.0;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

-(void)confirmationTapEvent
{
    if (self.selectedBlock) {
        self.selectedBlock(self.dataArray,self.dataServerArray);
    }
    
    [UIView animateWithDuration:0.5f animations:^{
        
        self.alpha = 0.0;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

-(SAproductUploadAPI *)productUploadAPI {
    if (!_productUploadAPI) {
        _productUploadAPI = [SAproductUploadAPI apiWithDelegate:self];
    }
    return _productUploadAPI;
}

@end

